package com.wg.wgaiagent.controller;

import com.wg.wgaiagent.app.ChatApp;
import com.wg.wgaiagent.common.BaseResponse;
import com.wg.wgaiagent.common.ErrorCode;
import com.wg.wgaiagent.common.ResultUtils;
import com.wg.wgaiagent.manager.DocumentLoaderTool;
import com.wg.wgaiagent.manager.UploadMdFile;
import com.wg.wgaiagent.model.entity.User;
import com.wg.wgaiagent.model.vo.ChatNomalVO;
import com.wg.wgaiagent.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

/**
 * @author with葡萄成熟时
 * @version 1.0
 */
@RestController
@RequestMapping("/ai")
public class ChatController {

    @Resource
    private UploadMdFile uploadMdFile;
    @Resource
    private DocumentLoaderTool documentLoaderTool;
    @Resource
    private ChatApp chatApp;
    @Resource
    private UserService userService;

    private final InMemoryChatMemoryRepository chatMemoryRepository;

    @Autowired
    public ChatController(InMemoryChatMemoryRepository chatMemoryRepository) {
        this.chatMemoryRepository = chatMemoryRepository;
    }

    /**
     * 同步调用 聊天应用
     *
     * @param message
     * @param chatId
     * @return
     */
    @PostMapping("/chat")
    public BaseResponse<ChatNomalVO> doChatWithAiSync(String message, String chatId, HttpServletRequest request) {
        ChatResponse chatResponse = chatApp.doChatWithTools(message, chatId);
        String text = chatResponse.getResult().getOutput().getText();
        Integer totalTokens = chatResponse.getMetadata().getUsage().getTotalTokens();
        User loginUser = userService.getLoginUser(request);
        if (loginUser.getToken() <= 0) {
            return ResultUtils.error(ErrorCode.valueOf("token不足"));
        }
        boolean b = userService.updateToken(loginUser, totalTokens);
        if (!b) {
            return ResultUtils.error(ErrorCode.valueOf("请求失败"));
        }

        ChatNomalVO chatNomalVO = new ChatNomalVO();
        chatNomalVO.setContent(text);
        chatNomalVO.setToken(totalTokens);

        return ResultUtils.success(chatNomalVO);

    }

    /**
     * 清除对话上下文记录
     *
     *
     * @param chatId
     * @return com.wg.wgaiagent.common.BaseResponse<java.lang.String>
     */
    @GetMapping("/chat/clean")
    public BaseResponse<String> cleanChatMemory(String chatId) {
        if (chatId == null) {
            return ResultUtils.error(ErrorCode.valueOf("chatId不能为空"));
        }
        try {
            chatMemoryRepository.deleteByConversationId(chatId);
        } catch (Exception e) {
            return ResultUtils.error(ErrorCode.valueOf("清理失败请重试"));
        }
        return ResultUtils.success("ok");

    }


}
